﻿using System;
using System.Web;
using System.Web.Security;
using TSharp.Core.Authentication.Facade;

namespace TSharp.Core.Authentication.Impl
{
    internal class AuthenticationService : IAuthenticationService
    {
        /// <summary>
        /// session 标识key
        /// </summary>
        public static string UserSessionKey = "tsharp_Session_user";

        private readonly IMembershipService _membershipservice;

        public AuthenticationService(IMembershipService membershipservice)
        {
            _membershipservice = membershipservice;
        }

        public IUser SignIn(HttpContextBase context, string userName, string password, bool createPersistentCookie)
        {
            ValidationUtil.ValidateRequiredStringValue(userName, "key");
            if (_membershipservice.ValidateUser(context, userName, password))
            {
                var user = _membershipservice.GetUser(context, userName, true);
                context.Session[UserSessionKey] = user;
                FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
                return user;
            }
            throw new AccountException(String.Format("用户'{0}'登录失败，帐号或密码错误", userName), AccountException.ErrorType.UnKown);
        }


        public IUser GetLoginUser(HttpContextBase context)
        {
            var user = context.Session[UserSessionKey] as IUser;
            if ((user == null || !user.IsOnline) &&
                (context.User != null && context.User.Identity != null && context.User.Identity.IsAuthenticated))
            {
                //用户已验证
                string username = context.User.Identity.Name;
                user = _membershipservice.GetUser(context, username, true);
                context.Session[UserSessionKey] = user;
            }
            return user;
        }

        public void SignOut(HttpContextBase context)
        {
            context.Session.Remove(UserSessionKey);
            FormsAuthentication.SignOut();
        }

        public bool IsAuthenticated(HttpContextBase contextBase)
        {
            return contextBase.User != null && contextBase.User.Identity != null &&
                   contextBase.User.Identity.IsAuthenticated;
        }

        public void RedirectUrl(HttpContextBase ContextBase)
        {
            //FormsAuthentication.GetRedirectUrl（） 的参数createPersistentCookie 是无用的，ms的bug
            ContextBase.Response.Redirect(FormsAuthentication.GetRedirectUrl(ContextBase.User.Identity.Name, false));
        }

        public void IsAuthenticatedAndRedirectUrl(HttpContextBase ContextBase)
        {
            if (IsAuthenticated(ContextBase))
                RedirectUrl(ContextBase);
        }
    }
}